# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
# Name:         config.py
# Purpose:      The main frame
#
# Author:       Zhang Kun
#
# Created:      1/21/08
# Copyright:    (c) 2007-2008 HanMingSoft, Inc.
# License:      Apache License v2.0
#----------------------------------------------------------------------------

import wx
import wx.lib.flatnotebook as fnb
import wx.html as  html
import os
from wx.lib import buttons
from config import *

class MenuWindow(html.HtmlWindow):
    def __init__(self, parent):
        html.HtmlWindow.__init__(self, parent, id=-1, style=wx.NO_FULL_REPAINT_ON_RESIZE)
        if "gtk2" in wx.PlatformInfo:
            self.SetStandardFonts()
    def OnLinkClicked(self, linkinfo):
        #super(MenuWindow, self).OnLinkClicked(linkinfo)
        method = getattr(wx.GetApp().GetTopWindow(), linkinfo.GetHref())
        if method:
            method()

class MainFrame(wx.Frame):
    forms = {}
    def __init__(self):
        """Create the MainFrame."""
        wx.Frame.__init__(self, parent=None, title=APP_TITLE, size=FRAME_SIZE,
                          style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
        self.MakeMenu()
        self.MakeToolBar()
        self.MakeStatueBar()
        self.LayoutItems()
        self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnPageClosing)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Center()

    def OnClose(self, event):
        ret = wx.MessageDialog(self, u'您确认要退出系统吗？', u'提示',
                            wx.YES_NO | wx.ICON_QUESTION).ShowModal()
        #ret = wx.MessageBox(u'您确认要退出系统吗？', u"提示", wx.YES_NO | wx.ICON_QUESTION)
        if ret == wx.ID_YES:
            self.Destroy()

    def MakeMenu(self):
        menuBar = wx.MenuBar()
        menu = wx.Menu()
        menuBar.Append(menu, u"基本信息")
        item = wx.MenuItem(menu, wx.ID_ANY, u"客户信息", u"客户信息管理")
        self.Bind(wx.EVT_MENU, self.OnCustomerInfo, item)
        menu.AppendItem(item)
        
        menu = wx.Menu()
        menuBar.Append(menu, u"单据录入")
        menu = wx.Menu()
        menuBar.Append(menu, u"采购分析")
        menu = wx.Menu()
        menuBar.Append(menu, u"库存分析")
        menu = wx.Menu()
        menuBar.Append(menu, u"销售分析")
        menu = wx.Menu()
        menuBar.Append(menu, u"月末盘点")
        menu = wx.Menu()
        menuBar.Append(menu, u"月末结帐")

        menu = wx.Menu()
        item = wx.MenuItem(menu, wx.ID_ANY, u"关于...", u"显示关于对话框")
        self.Bind(wx.EVT_MENU, self.OnAbout, item)
        menu.AppendItem(item)
        menuBar.Append(menu, u"帮助")
        self.SetMenuBar(menuBar)
        
    def OnCustomerInfo(self, event):
        self.EditCustomerInfo()

    def EditCustomerInfo(self, id=None):
        # wx.MessageDialog(self, u'欢迎使用客户信息管理。', u'提示',
                           # wx.OK | wx.ICON_ERROR
                           # ).ShowModal()
        from customer import CustomerForm
        if 'customer_form' in self.forms:
            form = self.forms['customer_form'][1]
            if id:
                form.Edit(id)            
            self.book.SetSelection(self.forms['customer_form'][0])
        else:
            print 'New Customer'
            form = CustomerForm(self.book)
            if id:
                form.Edit(id)
            self.book.AddPage(form, u"客户信息编辑")
            self.forms['customer_form'] = (self.book.GetSelection(), form)

    def ShowCustomerView(self):
        from customer import CustomerView

        if 'customer_view' in self.forms:
            self.book.SetSelection(self.forms['customer_view'][0])
        else:
            print 'New Customer'
            view = CustomerView(self.book)
            self.book.AddPage(view, u"客户信息一览")
            self.forms['customer_view'] = (self.book.GetSelection(), view)

    def MakeToolBar(self):
        toolBar = self.CreateToolBar()
        tsize = (24, 24)
        toolBar.SetToolBitmapSize(tsize)

        bmp =  wx.ArtProvider.GetBitmap(wx.ART_GO_HOME, wx.ART_TOOLBAR, tsize)
        toolBar.AddLabelTool(10, u"业务导航", bmp, shortHelp=u"业务导航")
        toolBar.AddSeparator()

        bmp =  wx.ArtProvider.GetBitmap(wx.ART_EXECUTABLE_FILE, wx.ART_TOOLBAR, tsize)
        toolBar.AddLabelTool(20, u"刷新", bmp, shortHelp=u"刷新")
        toolBar.AddSeparator()

        bmp =  wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_TOOLBAR, tsize)
        toolBar.AddLabelTool(30, u"新建", bmp, shortHelp=u"新建")

        bmp =  wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR, tsize)
        toolBar.AddLabelTool(40, u"保存", bmp, shortHelp=u"保存")

        bmp =  wx.ArtProvider.GetBitmap(wx.ART_PRINT, wx.ART_TOOLBAR, tsize)
        toolBar.AddLabelTool(50, u"打印", bmp, shortHelp=u"打印")

        bmp =  wx.ArtProvider.GetBitmap(wx.ART_DELETE, wx.ART_TOOLBAR, tsize)
        toolBar.AddLabelTool(60, u"删除", bmp, shortHelp=u"删除")
        toolBar.AddSeparator()

        bmp =  wx.ArtProvider.GetBitmap(wx.ART_QUIT, wx.ART_TOOLBAR, tsize)
        toolBar.AddLabelTool(70, u"退出", bmp, shortHelp=u"退出")
        toolBar.Bind(wx.EVT_TOOL, self.OnToolClick)
        toolBar.Realize()

    def OnToolClick(self, event):
        print event.GetId()
        id = event.GetId()
        if id == 10:
            self.book.SetSelection(0)
        elif id == 20:
            for k, v in self.forms.items():
                print k
                if v[0] == self.book.GetSelection():
                    if hasattr(v[1], 'Refresh'):
                        v[1].Refresh()
        elif id == 30:
            pass
        elif id == 40:
            for k, v in self.forms.items():
                print k
                if v[0] == self.book.GetSelection():
                    if hasattr(v[1], 'Save'):
                        v[1].Save()
        elif id == 50:
            for k, v in self.forms.items():
                print k
                if v[0] == self.book.GetSelection():
                    if hasattr(v[1], 'Print'):
                        v[1].Print()
        elif id == 70:
            self.Close()

    def MakeStatueBar(self):
        statueBar = self.CreateStatusBar()
        statueBar.SetFieldsCount(3)
        statueBar.SetStatusWidths([-2, -1, -2])
        statueBar.SetStatusText(wx.GetApp().username + u"，你好！", 1)        

    def LayoutItems(self):
        #mainSizer = wx.BoxSizer(wx.VERTICAL)
        #self.SetSizer(mainSizer)
        #bookStyle = fnb.FNB_NODRAG | fnb.FNB_NO_X_BUTTON
        bookStyle = fnb.FNB_NODRAG | fnb.FNB_BOTTOM
        self.book = fnb.FlatNotebook(self, wx.ID_ANY, style=bookStyle)
        #mainSizer.Add(self.book)
        self.book.AddPage(self.CreateNavigaterWindow(), u"业务面板")

    def CreateNavigaterWindow(self):
        splitter = wx.SplitterWindow(self, -1)
        #sty = wx.BORDER_THEME
        sty = wx.BORDER_SIMPLE
        leftWin = self.CreateLeftWindow(splitter)
        rightWin = self.CreateRightWindow(splitter)
        splitter.SetMinimumPaneSize(200)
        splitter.SplitVertically(leftWin, rightWin, 200)
        return splitter
        
    def CreateRightWindow(self, parent):
        panel = wx.Panel(parent, style=wx.BORDER_SIMPLE | wx.EXPAND)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.menuHtml = MenuWindow(panel)
        sizer.Add(self.menuHtml, 1, wx.EXPAND)
        self.menuHtml.HistoryClear()
        self.menuHtml.LoadPage('htm/index.htm')
        panel.SetSizer(sizer)
        return panel

    def CreateLeftWindow(self, parent):
        panel = wx.Panel(parent, style=wx.BORDER_SIMPLE | wx.EXPAND)
        sizer = wx.BoxSizer(wx.VERTICAL)
        imageList = wx.ImageList(32, 32)
        rootIdx = imageList.Add(wx.Image('img/index.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap())
        commonIdx = imageList.Add(wx.Image('img/common.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap())
        masterIdx = imageList.Add(wx.Image('img/master.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap())
        purchaseIdx = imageList.Add(wx.Image('img/purchase.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap())
        saleIdx = imageList.Add(wx.Image('img/sale.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap())
        stockIdx = imageList.Add(wx.Image('img/stock.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap())
        financeIdx = imageList.Add(wx.Image('img/finance.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap())
        systemIdx = imageList.Add(wx.Image('img/system.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap())
        self.imageList = imageList
        
        cmdTree = wx.TreeCtrl(panel, -1)
        sizer.Add(cmdTree, 1, wx.EXPAND)
        
        cmdTree.SetImageList(self.imageList)
        root = cmdTree.AddRoot(u"业务一览", image=rootIdx, data=wx.TreeItemData("htm/index.htm"))
        #cmdTree.SetItemImage(root, rootIdx, wx.TreeItemIcon_Normal)
        
        cmdTree.AppendItem(root, u"常用业务", image=commonIdx, data=wx.TreeItemData("htm/common.htm"))
        cmdTree.AppendItem(root, u"基本信息", image=masterIdx, data=wx.TreeItemData("htm/master.htm"))
        cmdTree.AppendItem(root, u"进货管理", image=purchaseIdx, data=wx.TreeItemData("htm/purchase.htm"))
        cmdTree.AppendItem(root, u"销售管理", image=saleIdx, data=wx.TreeItemData("htm/sale.htm"))
        cmdTree.AppendItem(root, u"库存管理", image=stockIdx, data=wx.TreeItemData("htm/stock.htm"))
        cmdTree.AppendItem(root, u"财务管理", image=financeIdx, data=wx.TreeItemData("htm/finance.htm"))
        cmdTree.AppendItem(root, u"系统管理", image=systemIdx, data=wx.TreeItemData("htm/system.htm"))
        cmdTree.Expand(root)
        self.cmdTree = cmdTree
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnTreeSelChanged, self.cmdTree)

        sizer.Add(wx.StaticText(panel, -1, u"快捷方式", size=(100, 25)), 0, wx.EXPAND)
        shortcutList = wx.ListCtrl(panel, -1)
        sizer.Add(shortcutList, 1, wx.EXPAND)
        
        panel.SetSizer(sizer)
        return panel
        
    def OnTreeSelChanged(self, event):
        item = event.GetItem()
        if item: 
            page = self.cmdTree.GetItemData(item).GetData()
            print page
            if page:
                self.menuHtml.HistoryClear()
                if os.path.exists(page):
                    self.menuHtml.LoadPage(page)

    def OnPageClosing(self, event):
        if event.GetSelection() == 0:
            #print "Can't delete this page."
            event.Veto()
            return
        for key, form in self.forms.items():
            if form[0] == event.GetSelection():
                del self.forms[key]
#        for key, view in self.views.items():
#            if view[0] == event.GetSelection():
#                del self.views[key]
        event.Skip()

    def OnAbout(self, event):
        #from wx.lib.wordwrap import wordwrap
        info = wx.AboutDialogInfo()
        info.Name = "Sharp MIS"
        info.Version = "0.0.1"
        info.Copyright = "(C) 2008 HanMingSoft"
        info.Description = u"欢迎使用免费开源的企业进销存系统"
        info.WebSite = ("http://hanmingsoft.com", u"请光临我们的主页")
        info.Developers = ["zhang kun"]
        #info.License = wordwrap(open("license.txt").read(), 500, wx.ClientDC(self))
        info.License = open("license.txt").read()
        wx.AboutBox(info)

if __name__ == "__main__":
    app = wx.PySimpleApp()
    app.username = 'Test'
    app.frame = MainFrame()
    app.frame.Show()
    app.MainLoop()
